import grails.converters.XML

class MarketBuyController {

    def index = { }

    def buy = {
        def currentProduct = new Product()
        def providers = ProviderRegistry.findAll()
        providers.each{ provider ->
            print(provider.fullAddress)
            def url = provider.fullAddress+"/provider/buy/"+params.code
            def post = new Post("url":url)
            def xmlResponse = post.getText()
            if(!xmlResponse.equals("<status>false<status>")) {
                def xml = new XmlSlurper().parseText(xmlResponse)
                println "MarketBuyController-buy ("+url+") "+xmlResponse
                xml.each { p ->
                    if(p.code.text().equals(params.code)) {
                        println "MarketBuyController-buy ("+url+") "+xml
                        currentProduct.name = p.name.text()
                        currentProduct.address = p.address.text()
                        currentProduct.code = p.code.text()
                        currentProduct.address = p.address.text()
                        currentProduct.price = Double.parseDouble(p.price.text())
                        currentProduct.delivery = Integer.parseInt(p.delivery.text())
                        currentProduct.available = Boolean.parseBoolean(p.available.text())
                    }
                }
            }
        }
        render currentProduct as XML
    }

    def findByName = {
        def products = new ArrayList()
        def xml
        def providers = ProviderRegistry.findAll()
        providers.each{ provider ->
            def url = provider.fullAddress+"/provider/xml/product/searchByName/"+params.name
            def get = new Get("url":url)
            def xmlResponse = get.getText()
            println "MarketBuyController-findByName ("+url+") "+xmlResponse
            xml = new XmlSlurper().parseText(xmlResponse)
            xml.product.each { p ->
                def currentProduct = new Product()
                currentProduct.name = p.name.text()
                currentProduct.address = p.address.text()
                currentProduct.code = p.code.text()
                currentProduct.price = Double.parseDouble(p.price.text())
                currentProduct.delivery = Integer.parseInt(p.delivery.text())
                currentProduct.available = Boolean.parseBoolean(p.available.text())
                products.add(currentProduct)
            }
        }
        render products as XML
    }
}
